<template>
  <div class="hp100 flex-column">
    <div class="mb10 flex-between">
      <Input
        v-model.trim="user"
        class="w180"
        placeholder="请输入昵称搜索"
        clearable
        @on-change="debounceQuery"
      ></Input>
      <div>
        <!--<Tag type="border" color="success">在线人数： {{onlineNum}}</Tag>-->
        <!--<Tag type="border" color="primary">接入人数： {{loginNum}}</Tag>-->
        <!-- disabledBatchDeploy ||  -->
        <Button
          type="warning"
          :loading="pauseLoading"
          size="small"
          class="ml4"
          @click="startRecording"
          v-if="screenRecording == 1 &&!videoStart"
          >屏幕录制</Button
        >
        <Button
          type="warning"
          :loading="pauseLoading"
          size="small"
          class="ml4"
          @click="stopRecording"
          v-if="screenRecording == 1 && !!videoStart"
          >结束录制</Button
        >
        <Button
          type="primary"
          size="small"
          v-if="status !== 2 && !(batchDeployLoading || disbledAllBtn || type === '作业')"
          @click="deployClass()"
          >全部部署</Button
        >
        <Poptip
          confirm
          title="确定销毁选中的环境？"
          @on-ok="batchExperimentDestroy"
          transfer
          word-wrap
          width="200"
          v-else
        >
          <Button
            type="error"
            size="small"
            v-if="!(disabledBatchDestroy || batchDestroyLoading || disbledAllBtn)"
            >批量销毁</Button
          >
        </Poptip>
        <Poptip
          confirm
          title="确定重置选中的环境吗？"
          @on-ok="batchExperimentRestart"
          transfer
          word-wrap
          width="200"
          v-if="cloudType !== 'h3c'"
        >
          <Button
            type="error"
            size="small"
            v-if="!(disabledBatchDestroy || batchDestroyLoading || disbledAllBtn)"
            class="ml4"
            >批量重置</Button
          >
        </Poptip>
      </div>
    </div>
    <!-- <div style="margin-bottom:10px" v-if="selectOpUsers.length > 0">
            已选择：
            <Tag
                v-for="user in selectOpUsers"
                :key="user.userId"
                color="blue"
                closable
                @on-close="handleClose(user)"
                >{{ user.userName }}</Tag
            >
        </div> -->
    <TableList
      ref="selectTable"
      :columns="getCol()"
      :row-class-name="rowClassName"
      :data="environList"
      :total="environTotal"
      :page.sync="environPage"
      :size.sync="environPageSize"
      @queryFun="getEnvironData"
      selectKey="userId"
      selectName="userName"
      :showSelectTag="true"
      :selection.sync="selectOpUsers"
    ></TableList>
    <!--  虚拟机列表，提供进入虚拟机-->
    <Modal
      v-model="vmsModal"
      :mask-closable="false"
      title="虚拟机列表"
      width="90"
    >
      <TableList
        :columns="vmsCol"
        :showPage="false"
        :page="1"
        :size="1000"
        :total="vmsList.length"
        :data="vmsRow(vmsList)"
        style="min-height: 200px; max-height: 80vh"
      ></TableList>
    </Modal>
  </div>
</template>

<script>
import RecordRTC from 'recordrtc'
import encryption from '@/libs/encryption.js';
import { debounce } from '@/libs/utils';
import { getCompanyUsersInfo } from '@/api/users';
import {
    deployClass_new,
    getClassUsers,
    updateClassStatus,
    batchExperimentDestroy,
    queryCheckScreenStatus,
    queryClassNumberList_new
} from '@/api/selfStudy/class_new.js';
import { pauseClassNumber } from '@/api/selfStudy/class.js'
import { getRecord } from '@/api/selfStudy/access.js';
import { getstatusbyprjid } from '@/api/drill';
import { courseDetail, expEnv, getVms, experimentDestroy } from '@/api/selfStudy/courseExp.js';
import { queryVmStatus, opVms, rebuildVm, rebootVm } from '@/api/remote.js';
import { getmemdata ,batchOpVm} from '@/api/drill_compete';
import {addRecord} from '@/api/selfStudy/record.js'
import vmsType from './vmsType';
import { mapState } from 'vuex'
import { getDictInfoByName } from '@/api/dict'
export default {
    name: 'deployClass',
    components: {
        vmsType
    },
    props: {
        classNumberId: {
            type: String,
            required: true
        },
        ecId: {
            type: String,
            required: true
        },
        ecName: {
            type: String,
            default: ''
        },
        classId: {
            //培训id
            type: String,
            required: true
        },
        classStatus: {
            //培训状态
            type: Number,
            default: 0
        },
        status: {
            //课节状态
            type: Number,
            default: 0
        },
        classType: {
            type: String,
            default: ''
        },
        type: {
            type: String,
            default: ''
        },
        step: {
            type: Number,
            default: 0
        },
        disbledAllBtn: {
            type: Boolean,
            default: false
        },
        classNumberInfo:{
            type:Object,
            default:()=>{}
        }
    },
    data() {
        let September = sessionStorage.getItem('November');
        September = JSON.parse(encryption.SelfUseDecrypt(September));
        return {
            USER_ID: September.userId,
            USER_Name: September.nickname,
            user: '',
            //				classUsers:[],
            //				allExpList:[],
            curExpId: '',
            //环境列表
            environList: [], //环境列表数据
            environTime: {}, //环境列表定时器
            ///index:0,
            //虚拟机列表
            vmsList: [],
            vmsModal: false, //虚拟机列表modal
            vmStatusTimeout: {}, //虚拟机状态定时器
            timeout: {}, //虚拟机资源监控定时器
            //当前课件数据
            exp: '',
            curExp: {},
            curExpId: '',
            // 计算index
            environCol: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'left'
                },
                {
                    title: '昵称',
                    key: 'nickname'
                },
                {
                    title: '类型',
                    key: 'type',
                    tooltip: true,
                    render: (h, params) => {
                        return h('span', params.row.type == 'T' ? '教师' : '学生');
                    }
                },
                {
                    title: '课件名',
                    key: 'ecName',
                    tooltip: true,
                    fun: this.gotoTopo
                },
                {
                    title: '部署状态',
                    key: 'deployStatus',
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'span',
                                {
                                    style: {
                                        color: this.$options.filters.statusFilter(
                                            params.row.deployStatus,
                                            'color'
                                        )
                                    }
                                },
                                this.$options.filters.statusFilter(params.row.deployStatus, 'text')
                            ),
                            h(
                                'Poptip',
                                {
                                    props: {
                                        trigger: 'hover',
                                        width: '300',
                                        content: params.row.errorMessage,
                                        wordWrap: true,
                                        transfer: true
                                    },
                                    style: {
                                        display: params.row.errorMessage ? '' : 'none'
                                    }
                                },
                                [
                                    h('Icon', {
                                        props: {
                                            type: 'ios-help-circle',
                                            color: 'rgb(203, 2, 54)',
                                            size: 16
                                        },
                                        style: {
                                            cursor: 'pointer'
                                        }
                                    })
                                ]
                            )
                        ]);
                    }
                },
                {
                    title: '是否在线',
                    key: 'onlline',
                    render: (h, params) => {
                        return h(
                            'Tag',
                            {
                                props: {
                                    type: 'border',
                                    color: params.row.online
                                        ? 'var(--status-yes)'
                                        : 'var(--status-no)'
                                }
                            },
                            params.row.online ? '在线' : '离线'
                        );
                    }
                },
                {
                    title: '是否接入虚拟机',
                    key: 'login',
                    render: (h, params) => {
                        let recordCol = [
                            {
                                title: '虚拟机名称',
                                key: 'name',
                                ellipsis: true,
                                tooltip: true
                            },
                            {
                                title: '昵称',
                                key: 'userName',
                                tooltip: true
                            },
                            //                  			{
                            //                  				title:'实例名称',
                            //                  				key:'instanceName',
                            //                  				tooltip:true
                            //                  			},
                            {
                                title: '接入方式',
                                key: 'protocol',
                                tooltip: true
                            },
                            {
                                type: 'showTime',
                                title: '登录时间',
                                key: 'connectTime',
                                width: 160,
                                tooltip: true
                            }
                        ];
                        //讲课
                        if (this.classType === 'prelection') {
                            if (params.row.login) {
                                return h('a', '已接入');
                            } else {
                                return h('span', '未接入');
                            }
                        } else {
                            //实操
                            let ele;
                            if (params.row.login) {
                                ele = h('a', '已接入');
                            } else {
                                ele = h('span', '未接入');
                            }
                            return h(
                                'Poptip',
                                {
                                    props: {
                                        width: 600,
                                        trigger: 'hover',
                                        transfer: true
                                    },
                                    style: {
                                        background: 'none!important'
                                    },
                                    on: {
                                        //		                    				'on-popper-show':() => {
                                        //		                    					this.getAccessRecord(params.row)
                                        //		                    				}
                                    }
                                },
                                [
                                    ele,
                                    h(
                                        'div',
                                        {
                                            slot: 'content'
                                        },
                                        [
                                            h('Table', {
                                                props: {
                                                    data: params.row.accessRecords || [],
                                                    columns: recordCol,
                                                    height: 300
                                                }
                                            })
                                        ]
                                    )
                                ]
                            );
                        }
                    }
                },
                {
                    title: '是否接入投屏',
                    key: 'screen',
                    render: (h, params) => {
                        if (params.row.screen) {
                            return h('a', '已接入');
                        } else {
                            return h('span', '未接入');
                        }
                    }
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 320,
                    opList: [
                        {
                            txt: '部署',
                            disabled: this.disDeploy,
                            fun: this.deployClass
                        },
                        {
                            txt: '销毁',
                            type: 'delete',
                            disabled: (data) => {
                                return !this.disbledAllBtn &&
                                    (data.deployStatus == 3 || data.deployStatus == 4) &&
                                    !data.disDestory
                                    ? false
                                    : true;
                            },
                            fun: this.doExperimentDestroy
                        },
                        {
                            txt: '重置',
                            // type: 'delete',
                            title: '你确定要重置吗?',
                            disabled: (data) => {
                                return !this.disbledAllBtn &&
                                    (data.deployStatus == 3 && !data.disDestory) ? false : true;
                            },
                            // style: {
                            //     display: this.cloudType === 'h3c' ? 'none' : ''
                            // },
                            fun: this.doExperimentRestart
                        },
                        {
                            txt: '查看实时投屏',
                            // show: (data) => {
                            //     let showFlag =
                            //         this.status == 1 || (this.step == 0 && data.type == 'T');
                            //     return (
                            //         data.type == 'S' && this.classType === 'prelection' && showFlag
                            //     );
                            // },
                            disabled: (data) => {
                                let isTeachStudent =
                                    data.type == 'S' && this.classType === 'teaching';
                                return isTeachStudent &&
                                    !this.disbledAllBtn &&
                                    data.deployStatus == 3 &&
                                    data.login &&
                                    !data.disDestory
                                    ? false
                                    : true;
                            },
                            fun: (data) => {
                                const { href } = this.$router.resolve({
                                    path: '/testScreen',
                                    query: {
                                        prjId: data.projectId,
                                        ecId: data.ecId,
                                        userId: data.userId,
                                        classId: this.classId
                                    }
                                });
                                window.openTrain(href, '_blank');
                            }
                        },
                        {
                            txt: '进入环境',
                            // show: (data) => {
                            //     let showFlag =
                            //         this.status == 1 || (this.step == 0 && data.type == 'T');
                            //     return (
                            //         !(data.type == 'S' && this.classType === 'prelection') &&
                            //         showFlag
                            //     );
                            // },
                            disabled: (data) => {
                                let isPrelectionStudent =
                                    data.type == 'S' && this.classType === 'prelection';

                                return !this.disbledAllBtn &&
                                    !isPrelectionStudent &&
                                    data.deployStatus == 3 &&
                                    !data.disDestory
                                    ? false
                                    : true;
                            },
                            fun: (data) => {
                                this.vmsModal = true;
                                this.curExpId = data.ecId;
                                this.curProjectId = data.projectId;
                                this.getVms(data.projectId);
                            }
                        }
                    ]
                }
            ],
            vmsCol: [
                {
                    type: 'index',
                    width: 60
                },
                {
                    title: '虚拟机名称',
                    key: 'name',
                    tooltip: true
                },
                //        {
                //          title:this.$t('VmType'),
                //          key:'vmType',
                //          align:'center',
                //        },
                {
                    title: '类型',
                    key: 'vzType',
                    tooltip: true
                },
                //			        {
                //			          title:this.$t('projectName'),
                //			          key:'projectName',
                //			          align:'center',
                //			        },
                // {
                //   title:'实例名称',
                //   key:'instance',
                //   align:'center',
                // },
                {
                    title: '状态',
                    key: 'status',
                    tooltip: true
                },
                //			        {
                //			          title:this.$t('HostIp'),
                //			          key:'hostIp',
                //			          align:'center',
                //			        },
                {
                    title: '主机名称',
                    key: 'host',
                    tooltip: true
                },
                {
                    title: '系统类型',
                    key: 'sysType',
                    tooltip: true
                },
                //			        {
                //			          title:this.$t('OSId'),
                //			          key:'osId',
                //			          align:'center',
                //			        },
                {
                    title: 'CPU总量',
                    key: 'cpu',
                    tooltip: true
                },
                {
                    title: '磁盘总量(GB)',
                    key: 'disk',
                    tooltip: true
                },
                {
                    title: '内存总量(MB)',
                    key: 'ram',
                    tooltip: true
                },
                {
                    title: 'CPU使用率(%)',
                    key: 'cpuVal',
                    render: (h, params) => {
                        return h(
                            'span',
                            {
                                // props: {
                                //     color: 'primary'
                                // }
                            },
                            params.row.cpuVal || '-'
                        );
                    }
                },
                {
                    title: '磁盘使用率(%)',
                    key: 'diskVal',
                    render: (h, params) => {
                        return h(
                            'span',
                            {
                                // props: {
                                //     color: 'primary'
                                // }
                            },
                            params.row.diskVal || '-'
                        );
                    }
                },
                {
                    title: '内存使用率(%)',
                    key: 'memVal',
                    render: (h, params) => {
                        return h(
                            'span',
                            {
                                props: {
                                    color: 'primary'
                                }
                            },
                            params.row.memVal || '-'
                        );
                    }
                },
                {
                    title: '用户名',
                    key: 'username',
                    tooltip: true
                },
                {
                    title: '密码',
                    key: 'password',
                    tooltip: true
                },
                {
                    type: 'selectTime',
                    title: '更新时间',
                    key: 'updated',
                    tooltip: true
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 300,
                    render: (h, params) => {
                        let action = '';
                        let text = '';
                        let type = '';
                        let disabled = false;
                        if (!params.row.status) {
                            return;
                        }
                        if (params.row.status == 'ACTIVE' || params.row.status == 'running') {
                            action = 'stop';
                            text = '关机';
                            type = 'primary';
                        } else if (
                            params.row.status == 'DOWN' ||
                            params.row.status == 'Stopped' ||
                            params.row.status == 'SHUTOFF'
                        ) {
                            action = 'start';
                            text = '开机';
                            type = 'primary';
                        } else {
                            text = '开机';
                            type = 'primary';
                            disabled = true;
                        }
                        return h('div', [
                            h(
                                'div',
                                {
                                    attrs: {
                                        id: 'selectBtn'
                                    }
                                },
                                [
                                    h(
                                        'Button',
                                        {
                                            props: {
                                                type: type,
                                                disabled: disabled
                                                //									size: 'small'
                                            },
                                            style: {
                                                borderRadius: '4px 0 0 4px'
                                            },
                                            on: {
                                                click: () => {
                                                    this.opVm(params.row.id, action);
                                                }
                                            }
                                        },
                                        text
                                    ),
                                    h(
                                        'Select',
                                        {
                                            props: {
                                                placeholder: '',
                                                transfer: true
                                            },
                                            style: {
                                                width: '20px'
                                            },
                                            on: {
                                                'on-select': (node) => {
                                                    let val = node.value
                                                    if (val == 'reboot-hard') {
                                                        this.rebootVm(params.row.id, 'hard_restart');
                                                    } else if (val == 'reboot-soft') {
                                                        this.rebootVm(params.row.id, 'soft_restart');
                                                    } else if (val == 'rebuild') {
                                                        this.rebuildVm(params.row.id);
                                                    }
                                                }
                                            }
                                        },
                                        [
                                            h(
                                                'Option',
                                                {
                                                    props: {
                                                        value: 'reboot-soft'
                                                    }
                                                },
                                                '软重启'
                                            ),
                                            h(
                                                'Option',
                                                {
                                                    props: {
                                                        value: 'reboot-hard'
                                                    }
                                                },
                                                '硬重启'
                                            ),
                                            h(
                                                'Option',
                                                {
                                                    props: {
                                                        value: 'rebuild'
                                                    }
                                                },
                                                '重置'
                                            )
                                        ]
                                    )
                                ]
                            ),
                            h(vmsType, {
                                props: {
                                    row: params.row,
                                    ecid: this.curExpId,
                                    classId: this.classId
                                },
                                style: {
                                    display: 'inline-block'
                                }
                            })
                        ]);
                    }
                }
            ],
            vmsRow (val) {
                let data = [];
                for (let i = 0; i < val.length; i++) {
                    data.push({
                        name: val[i]['name'],
                        vmType: val[i]['vmType'],
                        vzType: val[i]['vzType'],
                        projectId: val[i]['projectId'],
                        projectName: val[i]['projectName'],
                        osId: val[i]['osId'],
                        hostIp: val[i]['hostIp'],
                        host: val[i]['host'],
                        sysType: val[i]['sysType'],
                        instance: val[i]['instanceName'],
                        status: val[i]['status'],
                        updated: val[i]['updated'],
                        cpu: val[i]['cpu'],
                        disk: val[i]['disk'],
                        ram: val[i]['ram'],
                        diskVal: val[i]['diskVal'],
                        memVal: val[i]['memVal'],
                        cpuVal: val[i]['cpuVal'],
                        id: val[i]['id'],
                        accesses: val[i]['accesses'],
                        username: val[i]['accesses'][0].username,
                        password: val[i]['accesses'][0].password
                    });
                }
                return data;
            },
            environPage: 1,
            environPageSize: 10,
            environTotal: 0,
            //批量部署，批量销毁控制
            batchDestroyLoading: false,
            batchDeployLoading: false,
            //选择的操作用户
            selectOpUsers: [],
            interval: '',
            timeout: '',
            pauseLoading: false,
            videoStart: false,
            screenRecording: 0,
            recorderForm: {},
            videoPath: '',
            upLoadUrl: ``,
            video: null,
            recorder: null,
        };
    },
    computed: {
        ...mapState(['cloudType']),
        //			'onlineNum':function(){
        //				return this.environList.filter(env => env.user.online).length || 0;
        //			},
        //			'loginNum':function(){
        //				return this.environList.filter(env => env.login).length || 0;
        //		    },
        disabledBatchDeploy: function() {
            return this.selectOpUsers.length == 0; //this.environList.every(environ => environ.deployStatus == 3) || this.classInfo.type == '2';
        },
        disabledBatchDestroy: function() {
            return this.selectOpUsers.length == 0; //this.environList.every(environ => environ.deployStatus == 10) || this.classInfo.type == '2';
        }
    },
    watch: {
        classNumberId() {
            this.getEnvironData();
        }
    },
    filters: {
        typeFilter(val) {
            let str = '';
            switch (val) {
                case '1':
                    str = '实操模式';
                    break;
                case '2':
                    str = '讲课模式';
                    break;
                case '2':
                    str = '教学模式';
                    break;
            }
            return str;
        },
        //0-新建 3-部署成功 6-部署失败 8-删除失败9-部署中,10没有部署
        statusFilter(val, type) {
            let str = '';
            let color = '';
            switch (val) {
                case 0:
                    str = '未部署';
                    color = '#888';
                    break;
                case 3:
                    str = '部署成功';
                    color = '#06b649';
                    break;
                case 6:
                    str = '部署失败';
                    color = '#ff4242';
                    break;
                case 8:
                    str = '删除失败';
                    color = '#fa9901';
                    break;
                case 9:
                    str = '部署中';
                    color = '#06b649';
                    break;
                case 10:
                    str = '未部署';
                    	color = '#888';
                    break;
                case 14:
                    str = '清空部署失败';
                    color = '#ff8244';
                    break;
                default:
                    str = '未部署';
                    	color = '#888';
            }
            if (type == 'text') {
                return str;
            } else {
                return color;
            }
        }
    },
    mounted () {
        this.upLoadUrl = `${this.baseURL}/minio/upload/permanent`;
        this.getDictscreenRecording()
        if (this.classNumberId) {
            this.getEnvironData();
        }
        if (!navigator.getDisplayMedia && (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia)) {
            const error = 'Your browser does NOT support the getDisplayMedia API.'
            //不支持不显示屏幕录制
            this.screenRecording = 0
            throw new Error(error)
        }
        // this.getEnvironData();
        // this.interval = setInterval(() => {
        //     this.getEnvironData();
        // }, 10000);
    },
    beforeDestroy() {
        clearInterval(this.interval);
        clearTimeout(this.timeout);
    },
    methods: {
        getCol () {
            if (this.status === 2) {
                return this.environCol;
            } else {
                return this.environCol.slice(1);
            }
        },
        // getData (page, size) {
        //     this.environPage = page;
        //     this.environPageSize = 10 || size;
        //     if (this.classNumberId) {
        //         this.getEnvironData();
        //     }
        // },
        debounceQuery: debounce(function () {
            this.changeEnvironPage(1);
        }, 500),
        getEnvironData () {
            let params = {
                classNumberId: this.classNumberId,
                pageIndex: this.environPage,
                pageSize: this.environPageSize,
                nickname: this.user
            };
            queryClassNumberList_new(this.classId, params)
                .then(({ code, data, message }) => {
                    if (code == 1) {
                        this.environList = data.items.map((environ) => {
                            environ.ecId = this.ecId;
                            environ.ecName = this.ecName;
                            environ.type = environ.type == 'experimenter' ? 'S' : 'T';
                            environ.onlineText = environ.online ? '已登录' : '未登录';
                            environ.classId = this.classId;
                            return environ;
                        });
                        let userIds = this.selectOpUsers.map((user) => user.userId);
                        this.environList.forEach((environ) => {
                            if (userIds.includes(environ.userId)) {
                                environ._checked = true;
                            } else {
                                environ._checked = false;
                            }
                            environ._disabled = this.disSelect(environ);
                        });
                        this.environTotal = data.total;
                        clearTimeout(this.timeout);
                        this.timeout = setTimeout(() => {
                            this.getEnvironData();
                        }, 5000);
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                    this.$Message.error('获取环境信息列表失败');
                });
        },
        deployClass (environInfo) {
            let params = {};
            if (environInfo) {
                this.$set(environInfo, 'disDeploy', true);
                params.userId = environInfo.userId;
            } else {
                this.batchDeployLoading = true;
            }
            deployClass_new(this.classId, this.classNumberId, params)
                .then((data) => {
                    if (data.code == 1) {
                        this.$Message.info('操作成功');
                        if (environInfo) {
                            this.$set(environInfo, 'disDeploy', false);
                        } else {
                            this.batchDeployLoading = false;
                        }
                        this.getEnvironData();
                    } else {
                        if (environInfo) {
                            this.$set(environInfo, 'disDeploy', false);
                        } else {
                            this.batchDeployLoading = false;
                        }
                        this.$Message.warning(data.message);
                    }
                })
                .catch((error) => {
                    if (environInfo) {
                        this.$set(environInfo, 'disDeploy', false);
                    } else {
                        this.batchDeployLoading = false;
                    }
                });
        },
        batchDeployClass () {
            this.batchDeployLoading = true;
            const msg = this.$Message.loading({
                content: '请求中...',
                duration: 0
            });
            let expId = this.curExp.expid;
            let params = {
                userid: this.selectOpUsers.map((env) => env.userId), //filter(env => env.deployStatus == 6 || env.deployStatus == 10 || !env.deployStatus)
                ecid: [expId]
            };
            deployClass_new(this.classInfo.id, this.classInfo.type, this.classNumberId, params)
                .then((data) => {
                    if (data.code == 1) {
                        setTimeout(msg, 20);
                        setTimeout(() => {
                            this.$Message.success(data.message);
                        }, 20);
                        this.batchDeployLoading = false;
                        this.selectOpUsers = [];
                        this.getEnvironData();
                    } else {
                        setTimeout(msg, 20);
                        setTimeout(() => {
                            this.$Message.error(data.message);
                        }, 20);
                        this.batchDeployLoading = false;
                    }
                })
                .catch((error) => {
                    setTimeout(msg, 20);
                    setTimeout(() => {
                        this.$Message.error('请求失败');
                    }, 20);
                    this.batchDeployLoading = false;
                });
        },
        enterEnviron (projectId) {
            let routeData = this.$router.resolve({
                path: `/environment/${projectId}/${this.curExpId}`
            });
            window.openTrain(routeData.href, '_blank');
        },
        doExperimentDestroy (exp) {
            this.$set(exp, 'disDestory', true);
            let paramas = {
                projectId: exp.projectId,
                userId: exp.userId
            };
            experimentDestroy(paramas)
                .then((data) => {
                    if (data.code == 1) {
                        this.$Message.success('操作成功');
                        this.$set(exp, 'disDestory', false);
                        this.getEnvironData();
                    } else {
                        _this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    this.$Message.error(error);
                });
        },
        selectData (selection) {
            this.selectOpUsers = selection;
        },
        handleClose (user) {
            this.$refs['selectTable'].closeItem(user);
        },
        batchExperimentDestroy () {
            this.batchDestroyLoading = true;
            const msg = this.$Message.loading({
                content: '请求中...',
                duration: 0
            });
            let params = this.selectOpUsers
                .filter((environ) => environ.projectId)
                .map((environ) => {
                    return {
                        projectId: environ.projectId,
                        userId: environ.userId
                    };
                });
            batchExperimentDestroy(params)
                .then((data) => {
                    if (data.code == 1) {
                        setTimeout(msg, 20);
                        setTimeout(() => {
                            this.$Message.success('操作成功');
                        }, 20);
                        // this.selectOpUsers = [];
                        this.$refs['selectTable'].clearSelect();
                        this.getEnvironData();
                        this.batchDestroyLoading = false;
                    } else {
                        setTimeout(msg, 20);
                        setTimeout(() => {
                            this.$Message.error(data.message);
                        }, 20);
                        this.batchDestroyLoading = false;
                    }
                })
                .catch((error) => {
                    setTimeout(msg, 20);
                    setTimeout(() => {
                        this.$Message.error('请求失败');
                    }, 20);
                    this.batchDestroyLoading = false;
                });
        },
        	// 批量重置环境
        batchExperimentRestart () {
            this.batchDestroyLoading = true;
            const msg = this.$Message.loading({
                content: '请求中...',
                duration: 0
            });
            let promises = this.selectOpUsers.filter(environ => environ.projectId).map(environ => {
                return batchOpVm(environ.projectId, 'rebuild')
            })
            Promise.all(promises).then(res => {
                if (res.some(item => item.code != 1)) { // 有请求未成功
                    setTimeout(msg, 20);
                    setTimeout(() => {
                        this.$Message.warning('重置失败');
                    }, 20)
                    this.batchDestroyLoading = false;
                } else {
                    setTimeout(msg, 20);
                    setTimeout(() => {
                        this.$Message.success('重置成功');
                    }, 20)
                    this.selectOpUsers = [];
                    this.getEnvironData();
                    this.batchDestroyLoading = false;
                }
            }).catch(() => {
                setTimeout(msg, 20);
                setTimeout(() => {
                    this.$Message.error('批量重置异常');
                }, 20)
                this.batchDestroyLoading = false;
            })
        },
        	// 单个重置环境
        doExperimentRestart (item) {
            batchOpVm(item.projectId, 'rebuild').then(data => {
                if (data.code == 1) {
                    this.$Message.info('重置成功');
                    this.getEnvironData();
                } else {
                    this.$Message.warning(data.message);
                }
            }).catch(error => {
                this.$Message.error('环境重置异常');
            })
        },
        getVms (projectId) {
            getVms(projectId).then((data) => {
                if (data.code == 1) {
                    this.vmsList = data.attribute.vms;
                    this.getCPUData();
                    this.getVmStatus(data.attribute.vms.map((device) => device.id));
                } else {
                    this.vmsList = [];
                }
            });
        },
        getVmStatus (vms) {
          
          
            clearTimeout(this.vmStatusTimeout);
            if (vms.length <= 0) {
                return;
            }
            queryVmStatus(vms)
                .then((res) => {
                    if (res.code == 1 && res.list) {
                        this.vmsList.forEach((host) => {
                            res.list.forEach((vm) => {
                                if (host.id == vm.vmId) {
                                    this.$set(host, 'status', vm.status);
                                    return;
                                }
                            });
                        });
                        if (this.vmsModal) {
                            this.vmStatusTimeout = setTimeout(() => {
                                this.getVmStatus(vms);
                            }, 3000);
                        }
                    }
                })
                .catch((error) => {
                    // Alert("danger",error);
                });
        },
        cancelTimeout () {
            clearTimeout(this.vmStatusTimeout);
        },
        updateClassStatus (status) {
            updateClassStatus(this.curClass.id, status).then((data) => {
                if (data.code == 1) {
                    this.$Message.info(data.message);
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        rowClassName (row, index) {
            if (row.type === 'T') {
                // return 'demo-table-info-row';
            }
            return '';
        },
        changeEnvironPage (page) {
            this.environPage = page;
            this.getEnvironData();
        },
        disDeploy (environ) {
            let isPrelectionStudent = this.classType == 'prelection' && environ.type == 'S'; //讲课模式的学生,不需要部署
            let isHomework = this.type === '作业';
            //6：部署失败  10：未部署   / 部署状态为undefined /部署状态为0，但是有错误信息
            if (
                !this.disbledAllBtn &&
                !environ.disDeploy &&
                !isHomework &&
                !isPrelectionStudent &&
                this.classStatus !== 2 &&
                (environ.deployStatus == 6 ||
                    environ.deployStatus == 10 ||
                    !environ.deployStatus ||
                    (environ.deployStatus === 0 && environ.errorMessage))
            ) {
                return false;
            } else {
                return true;
            }
            //((params.row.deployStatus == 6 && !status1) || (params.row.deployStatus == 10 && !status1) || (!params.row.deployStatus && params.row.deployStatus != 0 && !status1)) ? false : true
        },
        //操作虚拟机
        opVm (id, action) {
            opVms(id, action)
                .then((data) => {
                    if (data.code == 1) {
                        this.$Message.info('操作成功');
                        this.getVms(this.curProjectId);
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('操作失败');
                });
        },
        //重置虚拟机
        rebuildVm (id) {
            rebuildVm(id)
                .then((data) => {
                    if (data.code == 1) {
                        this.$Message.info('操作成功');
                        this.getVms(this.curProjectId);
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('操作失败');
                });
        },
        //重启虚拟机
        rebootVm (id, type) {
            rebootVm(id, type)
                .then((data) => {
                    if (data.code == 1) {
                        this.$Message.info('操作成功');
                        this.getVms(this.curProjectId);
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('操作失败');
                });
        },
        clearTimeout () {
            clearTimeout(this.timeout);
        },
        getCPUData (host) {
            this.clearTimeout();
            let index = 0;
            this.vmsList.forEach((host) => {
                if (!host.instanceName) {
                    return;
                }
                getmemdata({
                    vmId: host.id
                })
                    .then((data) => {
                       // console.log('--------虚拟机的cpu-------',host.id,data)
                        if (data.code == 1) {
                            index++;
                            let response = data.data;
                            if (response.cpuUsage) {
                                this.$set(host, 'cpuRate', response.cpuUsage + '%');
                                this.$set(host, 'cpuVal', response.cpuUsage);
                            } else {
                                this.$set(host, 'cpuRate', '0%');
                                this.$set(host, 'cpuVal', 0);
                            }
                            if (response.diskUsage) {
                                this.$set(host, 'diskRate', response.diskUsage + '%');
                                this.$set(host, 'diskVal', response.diskUsage);
                            } else {
                                this.$set(host, 'diskRate', '0%');
                                this.$set(host, 'diskVal', 0);
                            }
                            if (response.memoryUsage) {
                                this.$set(host, 'memRate', response.memoryUsage + '%');
                                this.$set(host, 'memVal', response.memoryUsage);
                            } else {
                                this.$set(host, 'memRate', '0%');
                                this.$set(host, 'memVal', 0);
                            }
                            //                          if(response.netIncomingBytes){
                            //                              this.$set(host,'traffic',(response.netIncomingBytes +"/" +response.netOutgoingBytes));
                            //                          }else{
                            //                              this.$set(host,'traffic',"0.00/0.00");
                            //                          }
                            if (index == this.vmsList.length && this.timeout && this.vmsModal) {
                                this.timeout = setTimeout(() => {
                                    this.getCPUData(host);
                                }, 5000);
                            }
                        } else {
                            //this.$Message.error('查询失败')
                        }
                    })
                    .catch((error) => {
                        // Alert('danger',error.statusText)
                    });
            });
        },
        gotoTopo (scene) {
            if (scene.projectId && scene.deployStatus != 10) {
                window.openTrain(
                    `/TopoProject/index.html#/topologyDisplay/topologys?projectId=${scene.projectId}`
                );
            } else {
                this.$Message.warning('工程不存在！');
            }
        },
        disDestory (environ) {
            return !this.disbledAllBtn && environ.deployStatus == 3 && !environ.disDestory
                ? false
                : true;
        },
        disSelect (environ) {
            if (this.status === 0) {
                return this.disDeploy(environ);
            } else {
                return this.disDestory(environ);
            }
        },
        stopRecordingCallback () {
            // this.video.src = this.video.srcObject = null;
            // this.video.src = URL.createObjectURL(this.recorder.getBlob());
            //如果需要下载录屏文件可加上下面代码
            let url = URL.createObjectURL(this.recorder.getBlob())
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.style.display = "none";
            a.href = url;
            a.download = this.classNumberInfo.name + new Date().getTime() + ".mp4";
            a.click();
            window.URL.revokeObjectURL(url);
            //上传视频
            let that = this;
            let file = new File(
                [this.recorder.getBlob()],
                this.classNumberInfo.name+ new Date().getTime() + ".mp4",
                {
                    type: "video/mp4",
                }
            );
            console.log('file', file)
            let formData = new window.FormData()
            formData.append('file', file);
            this.axios({
                method: 'post',
                url: `${that.upLoadUrl}?visibility=company&bucket=videos&type=videos`,
                data: formData,
                headers: {
                    'Content-type': 'multipart/form-data',
                },
                timeout:0,
                onUploadProgress: progressEvent => {
                    // this.$Message.info('正在上传录屏')
                }
            }).then(res => {
                if (res.data.code == 1) {
                    // this.$Message.success('上传录屏成功')
                    this.recorderForm = res.data.info
                    this.videoPath = res.data.data
                    console.log(this.recorderForm, 1111111111111111);
                    this.addRecord()
                } else {
                    this.$Message.warning(res.data.message)
                }
            }).catch(err => {
                console.log(err)
            })
            this.recorder.screen.stop();
            this.recorder.destroy();
            this.recorder = null;
            this.videoStart = false;
        },
        addRecord () {
            let data = {
                fileId: this.recorderForm.id,
                fileSize: this.recorderForm.size,
                fileName: this.recorderForm.originalName,
                filePath: this.videoPath,
                classNumberId: this.classNumberInfo.classNumberId,
                ecId: this.classNumberInfo.exId
            }
            addRecord(data).then(res => {
                if (res.code == 1) {
                    this.$Message.success('上传录屏至教学班成功')
                } else {
                    this.$Message.success(res.message)
                }
            }).catch(err => {
                console.log(err)
            })
        },
        getDictscreenRecording () {
            let params = {
                name: 'screenRecording'
            }
            getDictInfoByName(params).then(res => {
                console.log(res);
                if (res.code == 1) {
                    this.screenRecording = res.attribute.data.value
                }
                else {
                    this.screenRecording = 0
                    this.$Message.warning('查询屏幕录制配置失败')
                };
            })
        },
        invokeGetDisplayMedia (success, error) {
            let displaymediastreamconstraints = {
                video: {
                    displaySurface: 'monitor', // monitor, window, application, browser
                    logicalSurface: true,
                    cursor: 'always' // never, always, motion
                }
            };
            // above constraints are NOT supported YET
            // that's why overridnig them
            displaymediastreamconstraints = {
                video: true
            };
            if (navigator.mediaDevices.getDisplayMedia) {
                navigator.mediaDevices.getDisplayMedia(displaymediastreamconstraints).then(success).catch(error);
            }
            else {
                navigator.getDisplayMedia(displaymediastreamconstraints).then(success).catch(error);
            }
        },
        startRecording () {
            this.captureScreen(screen => {
                // this.video.srcObject = screen;
                this.recorder = RecordRTC(screen, {
                    type: 'video'
                });
                this.recorder.startRecording();
                // release screen on stopRecording
                this.recorder.screen = screen;
                this.videoStart = true;
            });
        },
        stopRecording () {
            this.recorder.stopRecording(this.stopRecordingCallback);
        },
        captureScreen (callback) {
            this.invokeGetDisplayMedia((screen) => {
                this.addStreamStopListener(screen, () => {
                    //
                });
                callback(screen);
            }, function (error) {
                console.error(error);
                alert('已取消视频录制\n' + error);
            });
        },
        addStreamStopListener (stream, callback) {
            stream.addEventListener('ended', function () {
                callback();
                callback = function () { };
            }, false);
            stream.addEventListener('inactive', function () {
                callback();
                callback = function () { };
            }, false);
            stream.getTracks().forEach((track) => {
                track.addEventListener('ended', () => {
                    this.stopRecording()
                    callback();
                    callback = function () { };
                }, false);
                track.addEventListener('inactive', function () {
                    callback();
                    callback = function () { };
                }, false);
            });
        },

        pauseClassNumber () {
            this.pauseLoading = true
            pauseClassNumber(this.classNumberId).then(({ code, message }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.getClassNumberDetail()
                this.$emit('change-state', true)
                this.$Message.success('暂停课节成功')
            }).catch(() => {
                this.$Message.error('暂停课节异常')
            }).finally(() => {
                this.pauseLoading = false
            })
        },
    }
};
</script>

<style>
.ivu-table .demo-table-info-row td {
  background-color: #fff7e6;
  /*color: #ff9900;
        font-weight: bold;*/
}
#selectBtn {
  margin-right: 5px;
  display: inline-block;
}

#selectBtn .ivu-select-selection {
  border-radius: 0 4px 4px 0;
}

#selectBtn .ivu-select-arrow {
  right: 4px;
}

#selectBtn .ivu-select-selected-value {
  display: none;
}
</style>

